<!-- <!-- <template>
    <view class="order-list-container">
      <!-- 自定义导航栏 -->
      <view class="custom-navbar">
        <view class="navbar-left" @click="goBack">
          <u-icon name="arrow-left" size="20" color="#333"></u-icon>
        </view>
        <view class="navbar-title">订单列表</view>
        <view class="navbar-right">
          <u-icon 
            :name="isBatchMode ? 'close' : 'checkmark-circle'" 
            size="20" 
            :color="isBatchMode ? '#ff4444' : '#333'" 
            @click="toggleBatchMode"
          ></u-icon>
          <u-icon name="more-dot-fill" size="20" color="#333" @click="showMoreOptions"></u-icon>
        </view>
      </view>
  
      <!-- 搜索框 -->
      <view class="search-section">
        <u-search
          v-model="searchKeyword"
          placeholder="输入商品名称搜索"
          :show-action="false"
          :clearabled="true"
          bg-color="#f5f5f5"
          shape="round"
          @search="handleSearch"
        ></u-search>
      </view>
  
      <!-- 状态标签页 -->
      <view class="tab-section">
        <u-tabs
          :list="tabList"
          :current="currentTab"
          @change="handleTabChange"
          :active-color="activeColor"
          :inactive-color="inactiveColor"
          :bar-width="30"
          :bar-height="3"
          :bar-color="barColor"
          :font-size="28"
          :item-width="120"
        ></u-tabs>
      </view>
  
      <!-- 订单列表内容 -->
      <view class="order-content">
        <!-- 空状态 -->
        <view class="empty-state" v-if="orderList.length === 0">
          <view class="empty-illustration">
            <!-- 背景文档图标 -->
            <view class="document-bg">
              <view class="doc-lines">
                <view class="line line1"></view>
                <view class="line line2"></view>
                <view class="line line3"></view>
              </view>
            </view>
            <!-- 人物图标 -->
            <view class="person">
              <view class="head"></view>
              <view class="body">
                <view class="top"></view>
                <view class="pants"></view>
              </view>
              <view class="ladder">
                <view class="ladder-left"></view>
                <view class="ladder-right"></view>
                <view class="ladder-step1"></view>
                <view class="ladder-step2"></view>
              </view>
              <view class="paint-roller"></view>
            </view>
            <!-- 装饰植物 -->
            <view class="plant plant-left"></view>
            <view class="plant plant-right"></view>
          </view>
          <view class="empty-text">这里还没有相关订单~</view>
        </view>
  
        <!-- 订单列表 -->
        <view class="order-list" v-else>
          <view 
            class="order-item" 
            v-for="(order, index) in orderList" 
            :key="index"
            @click="isBatchMode ? selectOrder(order) : viewOrderDetail(order)"
            :class="{ 'batch-selected': isBatchMode && selectedOrders.find(item => item.id === order.id) }"
          >
            <!-- 订单头部 - 店铺信息和订单状态 -->
            <view class="order-header">
              <view class="shop-info">
                <view v-if="isBatchMode" class="batch-checkbox" @click.stop="selectOrder(order)">
                  <u-icon 
                    :name="selectedOrders.find(item => item.id === order.id) ? 'checkmark-circle-fill' : 'circle'" 
                    size="20" 
                    :color="selectedOrders.find(item => item.id === order.id) ? '#ff4444' : '#ccc'"
                  ></u-icon>
                </view>
                <u-icon name="shopping-cart" size="16" color="#333"></u-icon>
                <text class="shop-name">{{order.shopName}}</text>
              </view>
              <view class="order-status" :class="[getStatusClass(order.status)]">
                <text>{{getStatusText(order.status)}}</text>
              </view>
            </view>
            
            <!-- 订单商品信息 -->
            <view class="order-goods">
              <image class="goods-image" :src="order.goodsImage" mode="aspectFill"></image>
              <view class="goods-info">
                <view class="goods-name">{{order.goodsName}}</view>
                <view class="goods-specs">{{order.goodsSpecs}}</view>
                <view class="goods-price-count">
                  <text class="goods-price">¥{{order.goodsPrice}}</text>
                  <text class="goods-count">x{{order.goodsCount}}</text>
                </view>
              </view>
            </view>
            
            <!-- 订单金额信息 -->
            <view class="order-amount">
              <text class="amount-text">共{{order.goodsCount}}件商品 合计：</text>
              <text class="amount-value">¥{{order.totalAmount}}</text>
              <text class="amount-shipping">(含运费¥{{order.shippingFee}})</text>
            </view>
            
            <!-- 订单操作按钮 -->
            <view class="order-actions">
              <view class="action-btn btn-secondary" @click.stop="cancelOrder(order)" v-if="order.status === 'pending'">
                <text>取消订单</text>
              </view>
              <view class="action-btn btn-secondary" @click.stop="viewLogistics(order)" v-if="order.status === 'shipped' || order.status === 'completed'">
                <text>查看物流</text>
              </view>
              <view class="action-btn btn-secondary" @click.stop="applyRefund(order)" v-if="order.status !== 'cancelled' && order.status !== 'refunding'">
                <text>申请退款</text>
              </view>
              <view class="action-btn btn-primary" @click.stop="payOrder(order)" v-if="order.status === 'pending'">
                <text>立即付款</text>
              </view>
              <view class="action-btn btn-primary" @click.stop="confirmReceipt(order)" v-if="order.status === 'shipped'">
                <text>确认收货</text>
              </view>
              <view class="action-btn btn-primary" @click.stop="reviewOrder(order)" v-if="order.status === 'completed' && !order.isReviewed">
                <text>评价订单</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 批量操作栏 -->
      <view class="batch-actions" v-if="isBatchMode">
        <view class="batch-info">
          <text>已选择 {{selectedOrders.length}} 个订单</text>
        </view>
        <view class="batch-buttons">
          <u-button 
            type="success" 
            size="small" 
            @click="handleBatchShip"
            :disabled="selectedOrders.length === 0"
          >批量发货</u-button>
          <u-button 
            type="default" 
            size="small" 
            @click="toggleBatchMode"
          >取消</u-button>
        </view>
      </view>
    </view>
  </template>
  
  <script>
import {get,post,del,put} from '../../utils/request.js'
  export default {
    name: 'OrderList',
    data() {
      return {
        searchKeyword: '',
        currentTab: 0,
        activeColor: '#ff4444',
        inactiveColor: '#333333',
        barColor: '#ff4444',
        tabList: [
          { name: '全部' },
          { name: '待付款' },
          { name: '待发货' },
          { name: '待收货' },
          { name: '已完成' }
        ],
        orderList: [], // 订单列表数据
        selectedOrders: [], // 选中的订单
        isBatchMode: false // 是否处于批量模式
      }
    },
    onLoad() {
      // 页面加载时获取订单数据
      this.getOrderList()
      
      // 监听订单状态更新事件
      uni.$on('orderStatusUpdated', this.handleOrderStatusUpdate)
    },
    
    onUnload() {
      // 页面卸载时移除事件监听
      uni.$off('orderStatusUpdated', this.handleOrderStatusUpdate)
    },
    onPullDownRefresh() {
      // 下拉刷新
      this.getOrderList();
      // 停止下拉刷新动画
      setTimeout(() => {
        uni.stopPullDownRefresh();
      }, 1000);
    },
    methods: {
		async fetchData() {
		      try {
				// const token = uni.setStorageSync('token', token);
		        const res = await get('/order/list/');
				console.log(88888888);
		        console.log(res);
		      } catch (err) {
		        console.error(err);
		      }
		    },

      // 返回上一页
      goBack() {
        uni.navigateBack({
          delta: 1
        })
      },
      
      // 显示更多选项
      showMoreOptions() {
        uni.showActionSheet({
          itemList: ['刷新', '设置', '帮助'],
          success: (res) => {
            console.log('选择了第' + (res.tapIndex + 1) + '个按钮')
          }
        })
      },
      
      // 搜索处理
      handleSearch(value) {
        console.log('搜索关键词:', value)
        this.searchKeyword = value
        // 如果有搜索关键词，调用搜索接口
        if (value.trim()) {
          this.searchOrders(value.trim());
        } else {
          // 没有搜索关键词时，获取全部订单
          this.getOrderList();
        }
      },
      
      // 搜索订单
      async searchOrders(keyword) {
        try {
          const res = await get('/orderst/list', { keyword: keyword });
          if (res && res.code === 200) {
            let orders = res.rows || [];
            console.log('搜索返回的订单数据:', orders);
            
            // 根据当前标签页过滤订单
            if (this.currentTab === 0) { // 全部订单
              this.orderList = this.formatOrderData(orders);
            } else if (this.currentTab === 1) { // 待付款
              this.orderList = this.formatOrderData(orders.filter(order => order.orderStatus === 0));
            } else if (this.currentTab === 2) { // 待发货
              this.orderList = this.formatOrderData(orders.filter(order => order.orderStatus === 1));
            } else if (this.currentTab === 3) { // 待收货
              this.orderList = this.formatOrderData(orders.filter(order => order.orderStatus === 2));
            } else if (this.currentTab === 4) { // 已完成
              this.orderList = this.formatOrderData(orders.filter(order => order.orderStatus === 3));
            }
            
            console.log('搜索后订单列表长度:', this.orderList.length);
          }
        } catch (error) {
          console.error('搜索订单失败:', error);
          uni.showToast({
            title: '搜索订单失败',
            icon: 'none'
          });
        }
      },
      
      // 标签页切换
      handleTabChange(e) {
        this.currentTab = e.index;
        console.log('当前选中的标签页索引:', this.currentTab); // 添加日志
        this.getOrderList();
      },
      
      // 获取订单列表
      getOrderList() {
        console.log('获取订单列表，当前标签页:', this.currentTab); // 添加日志
        // 调用接口获取真实订单数据
        this.fetchOrderData();
      },
      
      // 从接口获取订单数据
      async fetchOrderData() {
        try {
          const res = await get('/orderst/list', {});
          if (res && res.code === 200) {
            let orders = res.rows || [];
            console.log('接口返回的订单数据:', orders);
            console.log('当前标签页索引:', this.currentTab);
            
            // 根据当前标签页过滤订单
            let filteredOrders = [];
            
            // 添加详细的数据调试信息
            console.log('所有订单的状态值:', orders.map(order => ({
              id: order.orderId || order.orderNumber,
              status: order.orderStatus,
              statusType: typeof order.orderStatus
            })));
            
            if (this.currentTab === 0) { // 全部订单
              filteredOrders = orders;
              console.log('显示全部订单，数量:', filteredOrders.length);
            } else if (this.currentTab === 1) { // 待付款
              filteredOrders = orders.filter(order => {
                const status = parseInt(order.orderStatus) || parseInt(order.status) || 0;
                return status === 0;
              });
              console.log('显示待付款订单，数量:', filteredOrders.length);
            } else if (this.currentTab === 2) { // 待发货
              filteredOrders = orders.filter(order => {
                const status = parseInt(order.orderStatus) || parseInt(order.status) || 0;
                return status === 1;
              });
              console.log('显示待发货订单，数量:', filteredOrders.length);
            } else if (this.currentTab === 3) { // 待收货
              filteredOrders = orders.filter(order => {
                const status = parseInt(order.orderStatus) || parseInt(order.status) || 0;
                return status === 2;
              });
              console.log('显示待收货订单，数量:', filteredOrders.length);
            } else if (this.currentTab === 4) { // 已完成
              // 兼容字符串和数字类型的状态值
              filteredOrders = orders.filter(order => {
                const status = parseInt(order.orderStatus) || parseInt(order.status) || 0;
                return status === 3;
              });
              console.log('显示已完成订单，数量:', filteredOrders.length);
              console.log('已完成订单详情:', filteredOrders);
            }
            
            this.orderList = this.formatOrderData(filteredOrders);
            console.log('格式化后订单列表长度:', this.orderList.length);
          }
        } catch (error) {
          console.error('获取订单列表失败:', error);
          uni.showToast({
            title: '获取订单列表失败',
            icon: 'none'
          });
        }
      },
      
      // 格式化订单数据
      formatOrderData(orders) {
        return orders.map(order => ({
          id: order.orderId || order.orderNumber,
          shopName: 'Mall4j蓝海商城',
          status: this.mapOrderStatus(order.orderStatus),
          goodsImage: order.goodsimg || '/static/logo.png',
          goodsName: order.goodsname || '',
          goodsSpecs: order.goodsSpecs || '',
          goodsPrice: order.goodsprice || '0.00',
          goodsCount: parseInt(order.goodsnumber) || 0,
          totalAmount: (parseFloat(order.goodsprice || 0) * parseInt(order.goodsnumber || 0)).toFixed(2),
          shippingFee: (parseFloat(order.orderPostPrice || 0)).toFixed(2),
          isReviewed: false
        }));
      },
      
      // 映射订单状态
      mapOrderStatus(orderStatus) {
        const statusMap = {
          0: 'pending',    // 待付款
          1: 'paid',       // 待发货
          2: 'shipped',    // 待收货
          3: 'completed',  // 已完成
          4: 'cancelled',  // 已取消
          5: 'refunding'   // 退款中
        };
        return statusMap[orderStatus] || 'pending';
      },
      
      // 生成模拟订单数据
      generateMockOrders() {
        return [
          {
            id: '202311150001',
            shopName: '优品商城旗舰店',
            status: 'pending',
            goodsImage: '/static/logo.png',
            goodsName: '2023新款女装连衣裙气质显瘦',
            goodsSpecs: '颜色：蓝色；尺码：M',
            goodsPrice: '199.00',
            goodsCount: 1,
            totalAmount: '209.00',
            shippingFee: '10.00',
            isReviewed: false
          },
          {
            id: '202311150002',
            shopName: '数码科技专营店',
            status: 'paid',
            goodsImage: '/static/logo.png',
            goodsName: '智能手表多功能运动监测',
            goodsSpecs: '颜色：黑色；尺寸：标准',
            goodsPrice: '299.00',
            goodsCount: 1,
            totalAmount: '299.00',
            shippingFee: '0.00',
            isReviewed: false
          },
          {
            id: '202311150003',
            shopName: '家居日用专营店',
            status: 'shipped',
            goodsImage: '/static/logo.png',
            goodsName: '北欧风格简约餐具套装',
            goodsSpecs: '款式：四人套装；颜色：白色',
            goodsPrice: '128.00',
            goodsCount: 2,
            totalAmount: '266.00',
            shippingFee: '10.00',
            isReviewed: false
          },
          {
            id: '202311150004',
            shopName: '美妆护肤旗舰店',
            status: 'completed',
            goodsImage: '/static/logo.png',
            goodsName: '补水保湿护肤套装',
            goodsSpecs: '类型：干性肌肤；规格：正装',
            goodsPrice: '358.00',
            goodsCount: 1,
            totalAmount: '358.00',
            shippingFee: '0.00',
            isReviewed: true
          },
          {
            id: '202311150005',
            shopName: '运动户外专营店',
            status: 'cancelled',
            goodsImage: '/static/logo.png',
            goodsName: '专业户外登山背包',
            goodsSpecs: '容量：40L；颜色：军绿色',
            goodsPrice: '199.00',
            goodsCount: 1,
            totalAmount: '209.00',
            shippingFee: '10.00',
            isReviewed: false
          }
        ];
      },
      
      // 获取订单状态对应的样式类
      getStatusClass(status) {
        const statusMap = {
          'pending': 'status-pending',
          'paid': 'status-paid',
          'shipped': 'status-shipped',
          'completed': 'status-completed',
          'cancelled': 'status-cancelled',
          'refunding': 'status-refunding'
        };
        return statusMap[status] || '';
      },
      
      // 获取订单状态对应的文本
      getStatusText(status) {
        const statusMap = {
          'pending': '待付款',
          'paid': '待发货',
          'shipped': '待收货',
          'completed': '已完成',
          'cancelled': '已取消',
          'refunding': '退款中'
        };
        return statusMap[status] || '未知状态';
      },
      
      // 切换批量模式
      toggleBatchMode() {
        this.isBatchMode = !this.isBatchMode;
        if (!this.isBatchMode) {
          this.selectedOrders = [];
        }
      },
      
      // 选择订单
      selectOrder(order) {
        if (!this.isBatchMode) return;
        
        const index = this.selectedOrders.findIndex(item => item.id === order.id);
        if (index > -1) {
          this.selectedOrders.splice(index, 1);
        } else {
          this.selectedOrders.push(order);
        }
      },
      
      // 批量发货
      async handleBatchShip() {
        if (this.selectedOrders.length === 0) {
          uni.showToast({
            title: '请先选择要发货的订单',
            icon: 'none'
          });
          return;
        }
        
        // 检查选中的订单是否都是待发货状态
        const invalidOrders = this.selectedOrders.filter(order => {
          const status = parseInt(order.status) || 0;
          return status !== 1; // 1表示待发货状态
        });
        
        if (invalidOrders.length > 0) {
          uni.showToast({
            title: '只能对待发货状态的订单进行发货操作',
            icon: 'none'
          });
          return;
        }
        
        uni.showModal({
          title: '确认发货',
          content: `确定要对选中的 ${this.selectedOrders.length} 个订单进行发货操作吗？`,
          success: async (res) => {
            if (res.confirm) {
              await this.executeBatchShip();
            }
          }
        });
      },
      
      // 执行批量发货
      async executeBatchShip() {
        try {
          uni.showLoading({
            title: '发货中...'
          });
          
          const orderIds = this.selectedOrders.map(order => order.id);
          
          // 调用批量发货接口
          const response = await put('/orderst/batchShip', { orderIds });
          
          if (response && response.code === 200) {
            uni.showToast({
              title: '批量发货成功',
              icon: 'success'
            });
            
            // 清空选择
            this.selectedOrders = [];
            this.isBatchMode = false;
            
            // 刷新订单列表
            this.getOrderList();
          } else {
            throw new Error(response?.msg || '批量发货失败');
          }
        } catch (error) {
          console.error('批量发货失败:', error);
          uni.showToast({
            title: error.message || '批量发货失败，请重试',
            icon: 'none'
          });
        } finally {
          uni.hideLoading();
        }
      },
      
      // 查看订单详情
      viewOrderDetail(order) {
        uni.navigateTo({
          url: `/pages/order/order-detail?orderId=${order.id}`
        });
      },
      
      // 取消订单
      cancelOrder(order) {
        uni.showModal({
          title: '提示',
          content: '确定要取消该订单吗？',
          success: (res) => {
            if (res.confirm) {
              // 模拟取消订单操作
              uni.showToast({
                title: '订单已取消',
                icon: 'success'
              });
              // 刷新订单列表
              this.getOrderList();
            }
          }
        });
      },
      
      // 查看物流
      viewLogistics(order) {
        uni.showToast({
          title: '查看物流功能开发中',
          icon: 'none'
        });
      },
      
      // 申请退款
      applyRefund(order) {
        uni.navigateTo({
          url: `/pages/refund-list/refund-apply?orderId=${order.id}`
        });
      },
      
              // 支付订单
        payOrder(order) {
          console.log('准备支付订单:', order);
          // 跳转到支付页面，传递订单ID
          uni.navigateTo({
            url: `/pages/payment/payment?orderId=${order.id}`
          });
        },
      
      // 确认收货
      confirmReceipt(order) {
        uni.showModal({
          title: '提示',
          content: '确认已收到商品吗？',
          success: (res) => {
            if (res.confirm) {
              uni.showToast({
                title: '已确认收货',
                icon: 'success'
              });
              // 刷新订单列表
              this.getOrderList();
            }
          }
        });
      },
      
      // 评价订单
      reviewOrder(order) {
        uni.navigateTo({
          url: `/pages/order/order-review?id=${order.id}`
        });
      },
      
      // 处理订单状态更新
      handleOrderStatusUpdate(data) {
        const { orderId, oldStatus, newStatus } = data;
        
        console.log('收到订单状态更新:', data);
        console.log('当前标签页索引:', this.currentTab);
        console.log('订单状态变化:', oldStatus, '->', newStatus);
        
        // 显示提示
        uni.showToast({
          title: '订单状态已更新',
          icon: 'success'
        });
        
        // 立即刷新数据，确保显示最新状态
        this.refreshOrderList();
        
        // 根据状态变化提供相应的提示
        if (oldStatus === 0 && newStatus === 3) {
          // 从待付款变为已完成（支付成功）
          console.log('订单支付成功，准备提示用户切换到已完成标签页');
          setTimeout(() => {
            uni.showModal({
              title: '订单支付成功',
              content: '订单状态已更新为已完成，是否切换到"已完成"标签页查看？',
              showCancel: true,
              cancelText: '稍后查看',
              confirmText: '立即查看',
              success: (res) => {
                if (res.confirm) {
                  console.log('用户选择立即查看，切换到已完成标签页');
                  // 切换到"已完成"标签页
                  this.currentTab = 4;
                  this.refreshOrderList();
                }
              }
            });
          }, 1000);
        } else if (oldStatus === 1 && newStatus === 2) {
          // 从待发货变为待收货
          uni.showToast({
            title: '订单已发货',
            icon: 'success'
          });
        } else if (oldStatus === 2 && newStatus === 3) {
          // 从待收货变为已完成
          uni.showToast({
            title: '订单已完成',
            icon: 'success'
          });
        }
      },
      
      // 刷新订单列表
      refreshOrderList() {
        console.log('刷新订单列表，当前标签页:', this.currentTab);
        // 重新获取订单数据
        this.fetchOrderData();
        
        // 添加调试信息，确保数据刷新
        console.log('订单列表刷新完成，当前标签页:', this.currentTab);
        console.log('当前订单列表长度:', this.orderList.length);
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .order-list-container {
    min-height: 100vh;
    background-color: #ffffff;
  }
  
  .custom-navbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    background-color: #ffffff;
    border-bottom: 1rpx solid #f0f0f0;
    
    .navbar-left {
      width: 60rpx;
      display: flex;
      align-items: center;
    }
    
    .navbar-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333333;
    }
    
      .navbar-right {
    width: 120rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 20rpx;
  }
  }
  
  .search-section {
    padding: 20rpx 30rpx;
    background-color: #ffffff;
  }
  
  .tab-section {
    background-color: #ffffff;
    border-bottom: 1rpx solid #f0f0f0;
  }
  
  .order-content {
    flex: 1;
    padding: 40rpx 30rpx;
  }
  
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    
    .empty-illustration {
      position: relative;
      width: 400rpx;
      height: 400rpx;
      margin-bottom: 40rpx;
      
      .document-bg {
        position: absolute;
        top: 50rpx;
        left: 50rpx;
        width: 300rpx;
        height: 300rpx;
        background-color: #f8f8f8;
        border-radius: 20rpx;
        border: 2rpx solid #e0e0e0;
        
        .doc-lines {
          padding: 40rpx 30rpx;
          
          .line {
            height: 8rpx;
            background-color: #d0d0d0;
            border-radius: 4rpx;
            margin-bottom: 20rpx;
            
            &.line1 {
              width: 80%;
            }
            
            &.line2 {
              width: 60%;
            }
            
            &.line3 {
              width: 70%;
            }
          }
        }
      }
      
      .person {
        position: absolute;
        top: 80rpx;
        left: 120rpx;
        z-index: 2;
        
        .head {
          width: 40rpx;
          height: 40rpx;
          background-color: #ffb6c1;
          border-radius: 50%;
          margin: 0 auto 10rpx;
        }
        
        .body {
          .top {
            width: 60rpx;
            height: 40rpx;
            background-color: #ff4444;
            border-radius: 10rpx;
            margin: 0 auto 5rpx;
          }
          
          .pants {
            width: 50rpx;
            height: 50rpx;
            background-color: #666666;
            border-radius: 10rpx;
            margin: 0 auto;
          }
        }
        
        .ladder {
          position: absolute;
          top: 60rpx;
          left: -20rpx;
          width: 80rpx;
          height: 120rpx;
          
          .ladder-left, .ladder-right {
            position: absolute;
            width: 8rpx;
            height: 120rpx;
            background-color: #999999;
            
            &.ladder-left {
              left: 0;
            }
            
            &.ladder-right {
              right: 0;
            }
          }
          
          .ladder-step1, .ladder-step2 {
            position: absolute;
            width: 80rpx;
            height: 8rpx;
            background-color: #999999;
            
            &.ladder-step1 {
              top: 40rpx;
            }
            
            &.ladder-step2 {
              top: 80rpx;
            }
          }
        }
        
        .paint-roller {
          position: absolute;
          top: 20rpx;
          right: -30rpx;
          width: 60rpx;
          height: 20rpx;
          background-color: #ff4444;
          border-radius: 10rpx;
          
          &::after {
            content: '';
            position: absolute;
            top: -10rpx;
            left: 50%;
            transform: translateX(-50%);
            width: 20rpx;
            height: 20rpx;
            background-color: #ff4444;
            border-radius: 50%;
          }
        }
      }
      
      .plant {
        position: absolute;
        bottom: 0;
        width: 40rpx;
        height: 60rpx;
        background: linear-gradient(to top, #4caf50, #8bc34a);
        border-radius: 20rpx 20rpx 0 0;
        
        &::before {
          content: '';
          position: absolute;
          top: -10rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 30rpx;
          height: 30rpx;
          background-color: #4caf50;
          border-radius: 50%;
        }
        
        &.plant-left {
          left: 20rpx;
        }
        
        &.plant-right {
          right: 20rpx;
        }
      }
    }
    
    .empty-text {
      font-size: 28rpx;
      color: #999999;
      text-align: center;
    }
  }
  
  .order-list {
    .order-item {
      background-color: #ffffff;
      border-radius: 16rpx;
      margin-bottom: 20rpx;
      padding: 30rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      
      &.batch-selected {
        border: 2rpx solid #ff4444;
        background-color: rgba(255, 68, 68, 0.05);
        transform: scale(1.02);
      }
      
      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 20rpx;
        border-bottom: 1rpx solid #f0f0f0;
        
        .shop-info {
          display: flex;
          align-items: center;
          
          .batch-checkbox {
            margin-right: 20rpx;
            display: flex;
            align-items: center;
            cursor: pointer;
          }
          
          .shop-name {
            font-size: 28rpx;
            color: #333;
            margin-left: 10rpx;
          }
        }
        
        .order-status {
          font-size: 26rpx;
          padding: 6rpx 12rpx;
          border-radius: 20rpx;
          
          &.status-pending {
            color: #ff9800;
            background-color: rgba(255, 152, 0, 0.1);
          }
          
          &.status-paid {
            color: #2196f3;
            background-color: rgba(33, 150, 243, 0.1);
          }
          
          &.status-shipped {
            color: #9c27b0;
            background-color: rgba(156, 39, 176, 0.1);
          }
          
          &.status-completed {
            color: #4caf50;
            background-color: rgba(76, 175, 80, 0.1);
          }
          
          &.status-cancelled {
            color: #9e9e9e;
            background-color: rgba(158, 158, 158, 0.1);
          }
          
          &.status-refunding {
            color: #f44336;
            background-color: rgba(244, 67, 54, 0.1);
          }
        }
      }
      
      .order-goods {
        display: flex;
        padding: 20rpx 0;
        
        .goods-image {
          width: 160rpx;
          height: 160rpx;
          border-radius: 8rpx;
          background-color: #f5f5f5;
          flex-shrink: 0;
        }
        
        .goods-info {
          flex: 1;
          margin-left: 20rpx;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          
          .goods-name {
            font-size: 28rpx;
            color: #333;
            line-height: 1.4;
            margin-bottom: 10rpx;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }
          
          .goods-specs {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 10rpx;
          }
          
          .goods-price-count {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .goods-price {
              font-size: 28rpx;
              color: #333;
              font-weight: 500;
            }
            
            .goods-count {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
      }
      
      .order-amount {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f0f0f0;
        
        .amount-text {
          font-size: 26rpx;
          color: #666;
        }
        
        .amount-value {
          font-size: 30rpx;
          color: #ff4444;
          font-weight: 500;
          margin: 0 6rpx;
        }
        
        .amount-shipping {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .order-actions {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-top: 20rpx;
        gap: 20rpx;
        
        .action-btn {
          padding: 10rpx 20rpx;
          border-radius: 30rpx;
          font-size: 26rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          
          &.btn-primary {
            background-color: #ff4444;
            color: #ffffff;
          }
          
          &.btn-secondary {
            background-color: #ffffff;
            color: #666666;
            border: 1rpx solid #dddddd;
          }
        }
      }
    }
  }
  
  .batch-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
    border-top: 1rpx solid #f0f0f0;
    padding: 20rpx 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
    z-index: 1000;
    
    .batch-info {
      font-size: 28rpx;
      color: #333;
    }
    
    .batch-buttons {
      display: flex;
      gap: 20rpx;
    }
  }
  </style> -->
  <template>
    <view class="order-list-container">
      <!-- 自定义导航栏 -->
      <view class="custom-navbar">
        <view class="navbar-left" @click="goBack">
          <u-icon name="arrow-left" size="20" color="#333"></u-icon>
        </view>
        <view class="navbar-title">订单列表</view>
        <view class="navbar-right">
          <u-icon name="more-dot-fill" size="20" color="#333" @click="showMoreOptions"></u-icon>
        </view>
      </view>
  
      <!-- 搜索框 -->
      <view class="search-section">
        <u-search
          v-model="searchKeyword"
          placeholder="输入商品名称搜索"
          :show-action="false"
          :clearabled="true"
          bg-color="#f5f5f5"
          shape="round"
          @search="handleSearch"
        ></u-search>
      </view>
  
      <!-- 状态标签页 -->
      <view class="tab-section">
        <u-tabs
          :list="tabList"
          :current="currentTab"
          @change="handleTabChange"
          :active-color="activeColor"
          :inactive-color="inactiveColor"
          :bar-width="30"
          :bar-height="3"
          :bar-color="barColor"
          :font-size="28"
          :item-width="120"
        ></u-tabs>
      </view>
  
      <!-- 订单列表内容 -->
      <view class="order-content">
        <!-- 空状态 -->
        <view class="empty-state" v-if="orderList.length === 0">
          <view class="empty-illustration">
            <!-- 背景文档图标 -->
            <view class="document-bg">
              <view class="doc-lines">
                <view class="line line1"></view>
                <view class="line line2"></view>
                <view class="line line3"></view>
              </view>
            </view>
            <!-- 人物图标 -->
            <view class="person">
              <view class="head"></view>
              <view class="body">
                <view class="top"></view>
                <view class="pants"></view>
              </view>
              <view class="ladder">
                <view class="ladder-left"></view>
                <view class="ladder-right"></view>
                <view class="ladder-step1"></view>
                <view class="ladder-step2"></view>
              </view>
              <view class="paint-roller"></view>
            </view>
            <!-- 装饰植物 -->
            <view class="plant plant-left"></view>
            <view class="plant plant-right"></view>
          </view>
          <view class="empty-text">这里还没有相关订单~</view>
        </view>
  
        <!-- 订单列表 -->
        <view class="order-list" v-else>
          <view 
            class="order-item" 
            v-for="(order, index) in orderList" 
            :key="index"
            @click="viewOrderDetail(order)"
          >
            <!-- 订单头部 - 店铺信息和订单状态 -->
            <view class="order-header">
              <view class="shop-info">
                <u-icon name="shopping-cart" size="16" color="#333"></u-icon>
                <text class="shop-name">{{order.shopName}}</text>
              </view>
              <view class="order-status" :class="[getStatusClass(order.status)]">
                <text>{{getStatusText(order.status)}}</text>
              </view>
            </view>
            
            <!-- 订单商品信息 -->
            <view class="order-goods">
              <image class="goods-image" :src="order.goodsImage" mode="aspectFill"></image>
              <view class="goods-info">
                <view class="goods-name">{{order.goodsName}}</view>
                <view class="goods-specs">{{order.goodsSpecs}}</view>
                <view class="goods-price-count">
                  <text class="goods-price">¥{{order.goodsPrice}}</text>
                  <text class="goods-count">x{{order.goodsCount}}</text>
                </view>
              </view>
            </view>
            
            <!-- 订单金额信息 -->
            <view class="order-amount">
              <text class="amount-text">共{{order.goodsCount}}件商品 合计：</text>
              <text class="amount-value">¥{{order.totalAmount}}</text>
              <text class="amount-shipping">(含运费¥{{order.shippingFee}})</text>
            </view>
            
            <!-- 订单操作按钮 -->
            <view class="order-actions">
              <view class="action-btn btn-secondary" @click.stop="cancelOrder(order)" v-if="order.status === 'pending'">
                <text>取消订单</text>
              </view>
              <view class="action-btn btn-secondary" @click.stop="viewLogistics(order)" v-if="order.status === 'shipped' || order.status === 'completed'">
                <text>查看物流</text>
              </view>
              <view class="action-btn btn-secondary" @click.stop="applyRefund(order)" v-if="order.status !== 'cancelled' && order.status !== 'refunding'">
                <text>申请退款</text>
              </view>
              <view class="action-btn btn-primary" @click.stop="payOrder(order)" v-if="order.status === 'pending'">
                <text>立即付款</text>
              </view>
              <view class="action-btn btn-primary" @click.stop="confirmReceipt(order)" v-if="order.status === 'shipped'">
                <text>确认收货</text>
              </view>
              <view class="action-btn btn-primary" @click.stop="reviewOrder(order)" v-if="order.status === 'completed' && !order.isReviewed">
                <text>评价订单</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </template>
  
  <script>
import { getUserId } from '../../utils/auth.js';
import {get,post,del,put} from '../../utils/request.js'
  export default {
    name: 'OrderList',
    data() {
      return {
        searchKeyword: '',
        currentTab: 0,
        activeColor: '#ff4444',
        inactiveColor: '#333333',
        barColor: '#ff4444',
        tabList: [
          { name: '全部' },
          { name: '待付款' },
          { name: '待发货' },
          { name: '待收货' },
          { name: '已完成' }
        ],
        orderList: [], // 订单列表数据
		userId: Number(getUserId()),
      }
    },
    onLoad(options) {
      // 检查是否有URL参数指定标签页
      if (options.tab) {
        this.currentTab = parseInt(options.tab);
        console.log('从URL参数设置标签页:', this.currentTab);
      }
      
      // 页面加载时获取订单数据
      this.getOrderList()
      
      // 监听订单状态更新事件
      uni.$on('orderStatusUpdated', this.handleOrderStatusUpdate)
    },
    
    onUnload() {
      // 页面卸载时移除事件监听
      uni.$off('orderStatusUpdated', this.handleOrderStatusUpdate)
    },
    onPullDownRefresh() {
      // 下拉刷新
      this.getOrderList();
      // 停止下拉刷新动画
      setTimeout(() => {
        uni.stopPullDownRefresh();
      }, 1000);
    },
    methods: {
      async fetchData() {
        try {
          const res = await get('/order/list/');
          console.log(res);
        } catch (err) {
          console.error(err);
        }
      },
  
      // 返回上一页
      goBack() {
        uni.navigateBack({
          delta: 1
        })
      },
      
      // 显示更多选项
      showMoreOptions() {
        uni.showActionSheet({
          itemList: ['刷新', '设置', '帮助'],
          success: (res) => {
            console.log('选择了第' + (res.tapIndex + 1) + '个按钮')
          }
        })
      },
      
      // 搜索处理
      handleSearch(value) {
        console.log('搜索关键词:', value)
        this.searchKeyword = value
        // 如果有搜索关键词，调用搜索接口
        if (value.trim()) {
          this.searchOrders(value.trim());
        } else {
          // 没有搜索关键词时，获取全部订单
          this.getOrderList();
        }
      },
      
      // 搜索订单
      async searchOrders(keyword) {
        try {
          const res = await get('/orderst/list', { keyword: keyword });
          if (res && res.code === 200) {
            let orders = res.rows || [];
            console.log('搜索返回的订单数据:', orders);
            
            // 根据当前标签页过滤订单
            if (this.currentTab === 0) { // 全部订单
              this.orderList = this.formatOrderData(orders);
            } else if (this.currentTab === 1) { // 待付款
              this.orderList = this.formatOrderData(orders.filter(order => order.orderStatus === 0));
            } else if (this.currentTab === 2) { // 待发货
              this.orderList = this.formatOrderData(orders.filter(order => order.orderStatus === 1));
            } else if (this.currentTab === 3) { // 待收货
              this.orderList = this.formatOrderData(orders.filter(order => order.orderStatus === 2));
            } else if (this.currentTab === 4) { // 已完成
              this.orderList = this.formatOrderData(orders.filter(order => order.orderStatus === 3));
            }
            
            console.log('搜索后订单列表长度:', this.orderList.length);
          }
        } catch (error) {
          console.error('搜索订单失败:', error);
          uni.showToast({
            title: '搜索订单失败',
            icon: 'none'
          });
        }
      },
      
      // 标签页切换
      handleTabChange(e) {
        this.currentTab = e.index;
        console.log('当前选中的标签页索引:', this.currentTab);
        this.getOrderList();
      },
      
      // 获取订单列表
      getOrderList() {
        console.log('获取订单列表，当前标签页:', this.currentTab);
        this.fetchOrderData();
      },
      
      // 从接口获取订单数据
      async fetchOrderData() {
        try {
          const res = await get('/orderst/list', {});
          if (res && res.code === 200) {
            let orders = res.rows || [];
            console.log('接口返回的订单数据:', orders);
            console.log('当前标签页索引:', this.currentTab);
            
            let filteredOrders = [];
            
            if (this.currentTab === 0) { // 全部订单
              filteredOrders = orders;
            } else if (this.currentTab === 1) { // 待付款
              filteredOrders = orders.filter(order => {
                const status = parseInt(order.orderStatus) || parseInt(order.status) || 0;
                return status === 0;
              });
            } else if (this.currentTab === 2) { // 待发货
              filteredOrders = orders.filter(order => {
                const status = parseInt(order.orderStatus) || parseInt(order.status) || 0;
                return status === 1;
              });
            } else if (this.currentTab === 3) { // 待收货
              filteredOrders = orders.filter(order => {
                const status = parseInt(order.orderStatus) || parseInt(order.status) || 0;
                return status === 2;
              });
            } else if (this.currentTab === 4) { // 已完成
              filteredOrders = orders.filter(order => {
                const status = parseInt(order.orderStatus) || parseInt(order.status) || 0;
                return status === 3;
              });
            }
            
            this.orderList = this.formatOrderData(filteredOrders);
            console.log('格式化后订单列表长度:', this.orderList.length);
          }
        } catch (error) {
          console.error('获取订单列表失败:', error);
          uni.showToast({
            title: '获取订单列表失败',
            icon: 'none'
          });
        }
      },
      
      // 格式化订单数据
      formatOrderData(orders) {
        return orders.map(order => ({
          id: order.orderId || order.orderNumber,
          shopName: 'Mall4j蓝海商城',
          status: this.mapOrderStatus(order.orderStatus),
          goodsImage: order.goodsimg || '/static/logo.png',
          goodsName: order.goodsname || '',
          goodsSpecs: order.goodsSpecs || '',
          goodsPrice: order.goodsprice || '0.00',
          goodsCount: parseInt(order.goodsnumber) || 0,
          totalAmount: (parseFloat(order.goodsprice || 0) * parseInt(order.goodsnumber || 0)).toFixed(2),
          shippingFee: (parseFloat(order.orderPostPrice || 0)).toFixed(2),
          isReviewed: false
        }));
      },
      
      // 映射订单状态
      mapOrderStatus(orderStatus) {
        const statusMap = {
          0: 'pending',    // 待付款
          1: 'paid',       // 待发货
          2: 'shipped',    // 待收货
          3: 'completed',  // 已完成
        };
        return statusMap[orderStatus] || 'pending';
      },
      
      // 获取订单状态对应的样式类
      getStatusClass(status) {
        const statusMap = {
          'pending': 'status-pending',
          'paid': 'status-paid',
          'shipped': 'status-shipped',
          'completed': 'status-completed',
          'cancelled': 'status-cancelled',
          'refunding': 'status-refunding'
        };
        return statusMap[status] || '';
      },
      
      // 获取订单状态对应的文本
      getStatusText(status) {
        const statusMap = {
          'pending': '待付款',
          'paid': '待发货',
          'shipped': '待收货',
          'completed': '已完成',
          'cancelled': '已取消',
          'refunding': '退款中'
        };
        return statusMap[status] || '未知状态';
      },
      
      // 查看订单详情
      viewOrderDetail(order) {
        uni.navigateTo({
          url: `/pages/order/order-detail?orderId=${order.id}`
        });
      },
      
      // 取消订单
      cancelOrder(order) {
        uni.showModal({
          title: '提示',
          content: '确定要取消该订单吗？',
          success: (res) => {
            if (res.confirm) {
              uni.showToast({
                title: '订单已取消',
                icon: 'success'
              });
              this.getOrderList();
            }
          }
        });
      },
      
      // 查看物流
      viewLogistics(order) {
        uni.showToast({
          title: '查看物流功能开发中',
          icon: 'none'
        });
      },
      
      // 申请退款
      applyRefund(order) {
        uni.navigateTo({
          url: `/pages/refund-list/refund-apply?orderId=${order.id}`
        });
      },
      
      // 支付订单
      payOrder(order) {
        console.log('准备支付订单:', order);
        uni.navigateTo({
          url: `/pages/payment/payment?orderId=${order.id}`
        });
      },
      
      // 确认收货
      async confirmReceipt(order) {
        uni.showModal({
          title: '确认收货',
          content: '确认已收到商品吗？收货后订单状态将变为已完成',
          success: async (res) => {
            if (res.confirm) {
              await this.updateOrderStatusToCompleted(order);
            }
          }
        });
      },
      
      // 更新订单状态为已完成
      async updateOrderStatusToCompleted(order) {
        try {
          uni.showLoading({
            title: '更新订单状态...'
          });
          
          // 先获取当前订单状态
          const currentResponse = await get(`/orderst/${order.id}`);
          if (currentResponse.code !== 200) {
            throw new Error('获取当前订单状态失败');
          }
          
          const currentOrder = currentResponse.data;
          const oldStatus = currentOrder.orderStatus;
          
          // 更新订单状态为已完成(3)
          const updateData = {
            ...currentOrder,
            orderStatus: 3
          };
          
          const response = await put('/orderst', updateData);
          if (response.code === 200) {
            uni.hideLoading();
            uni.showToast({
              title: '确认收货成功！',
              icon: 'success'
            });
            
            // 发送状态更新事件
            uni.$emit('orderStatusUpdated', {
              orderId: order.id,
              oldStatus: oldStatus,
              newStatus: 3,
              message: '已确认收货'
            });
            
            // 刷新订单列表
            this.refreshOrderList();
          } else {
            throw new Error(response.msg || '确认收货失败');
          }
        } catch (error) {
          uni.hideLoading();
          console.error('确认收货失败:', error);
          uni.showToast({
            title: error.message || '确认收货失败',
            icon: 'none'
          });
        }
      },
      
      // 评价订单
      reviewOrder(order) {
        uni.navigateTo({
          url: `/pages/order/order-review?id=${order.id}`
        });
      },
      
      // 处理订单状态更新
      handleOrderStatusUpdate(data) {
        const { orderId, oldStatus, newStatus } = data;
        
        console.log('收到订单状态更新:', data);
        console.log('当前标签页索引:', this.currentTab);
        console.log('订单状态变化:', oldStatus, '->', newStatus);
        
        // 显示提示
        uni.showToast({
          title: '订单状态已更新',
          icon: 'success'
        });
        
        // 立即刷新数据，确保显示最新状态
        this.refreshOrderList();
        
        // 根据状态变化提供相应的提示
        if (oldStatus === 0 && newStatus === 3) {
          // 从待付款变为已完成（支付成功）
          console.log('订单支付成功，准备提示用户切换到已完成标签页');
          setTimeout(() => {
            uni.showModal({
              title: '订单支付成功',
              content: '订单状态已更新为已完成，是否切换到"已完成"标签页查看？',
              showCancel: true,
              cancelText: '稍后查看',
              confirmText: '立即查看',
              success: (res) => {
                if (res.confirm) {
                  console.log('用户选择立即查看，切换到已完成标签页');
                  // 切换到"已完成"标签页
                  this.currentTab = 4;
                  this.refreshOrderList();
                }
              }
            });
          }, 1000);
        } else if (oldStatus === 1 && newStatus === 2) {
          // 从待发货变为待收货
          uni.showToast({
            title: '订单已发货',
            icon: 'success'
          });
        } else if (oldStatus === 2 && newStatus === 3) {
          // 从待收货变为已完成
          uni.showToast({
            title: '订单已完成',
            icon: 'success'
          });
        }
      },
      
      // 刷新订单列表
      refreshOrderList() {
        console.log('刷新订单列表，当前标签页:', this.currentTab);
        // 重新获取订单数据
        this.fetchOrderData();
        
        // 添加调试信息，确保数据刷新
        console.log('订单列表刷新完成，当前标签页:', this.currentTab);
        console.log('当前订单列表长度:', this.orderList.length);
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .order-list-container {
    min-height: 100vh;
    background-color: #ffffff;
  }
  
  .custom-navbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    background-color: #ffffff;
    border-bottom: 1rpx solid #f0f0f0;
    
    .navbar-left {
      width: 60rpx;
      display: flex;
      align-items: center;
    }
    
    .navbar-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333333;
    }
    
    .navbar-right {
      width: 60rpx;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
  
  .search-section {
    padding: 20rpx 30rpx;
    background-color: #ffffff;
  }
  
  .tab-section {
    background-color: #ffffff;
    border-bottom: 1rpx solid #f0f0f0;
  }
  
  .order-content {
    flex: 1;
    padding: 40rpx 30rpx;
  }
  
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    
    .empty-illustration {
      position: relative;
      width: 400rpx;
      height: 400rpx;
      margin-bottom: 40rpx;
      
      .document-bg {
        position: absolute;
        top: 50rpx;
        left: 50rpx;
        width: 300rpx;
        height: 300rpx;
        background-color: #f8f8f8;
        border-radius: 20rpx;
        border: 2rpx solid #e0e0e0;
        
        .doc-lines {
          padding: 40rpx 30rpx;
          
          .line {
            height: 8rpx;
            background-color: #d0d0d0;
            border-radius: 4rpx;
            margin-bottom: 20rpx;
            
            &.line1 {
              width: 80%;
            }
            
            &.line2 {
              width: 60%;
            }
            
            &.line3 {
              width: 70%;
            }
          }
        }
      }
      
      .person {
        position: absolute;
        top: 80rpx;
        left: 120rpx;
        z-index: 2;
        
        .head {
          width: 40rpx;
          height: 40rpx;
          background-color: #ffb6c1;
          border-radius: 50%;
          margin: 0 auto 10rpx;
        }
        
        .body {
          .top {
            width: 60rpx;
            height: 40rpx;
            background-color: #ff4444;
            border-radius: 10rpx;
            margin: 0 auto 5rpx;
          }
          
          .pants {
            width: 50rpx;
            height: 50rpx;
            background-color: #666666;
            border-radius: 10rpx;
            margin: 0 auto;
          }
        }
        
        .ladder {
          position: absolute;
          top: 60rpx;
          left: -20rpx;
          width: 80rpx;
          height: 120rpx;
          
          .ladder-left, .ladder-right {
            position: absolute;
            width: 8rpx;
            height: 120rpx;
            background-color: #999999;
            
            &.ladder-left {
              left: 0;
            }
            
            &.ladder-right {
              right: 0;
            }
          }
          
          .ladder-step1, .ladder-step2 {
            position: absolute;
            width: 80rpx;
            height: 8rpx;
            background-color: #999999;
            
            &.ladder-step1 {
              top: 40rpx;
            }
            
            &.ladder-step2 {
              top: 80rpx;
            }
          }
        }
        
        .paint-roller {
          position: absolute;
          top: 20rpx;
          right: -30rpx;
          width: 60rpx;
          height: 20rpx;
          background-color: #ff4444;
          border-radius: 10rpx;
          
          &::after {
            content: '';
            position: absolute;
            top: -10rpx;
            left: 50%;
            transform: translateX(-50%);
            width: 20rpx;
            height: 20rpx;
            background-color: #ff4444;
            border-radius: 50%;
          }
        }
      }
      
      .plant {
        position: absolute;
        bottom: 0;
        width: 40rpx;
        height: 60rpx;
        background: linear-gradient(to top, #4caf50, #8bc34a);
        border-radius: 20rpx 20rpx 0 0;
        
        &::before {
          content: '';
          position: absolute;
          top: -10rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 30rpx;
          height: 30rpx;
          background-color: #4caf50;
          border-radius: 50%;
        }
        
        &.plant-left {
          left: 20rpx;
        }
        
        &.plant-right {
          right: 20rpx;
        }
      }
    }
    
    .empty-text {
      font-size: 28rpx;
      color: #999999;
      text-align: center;
    }
  }
  
  .order-list {
    .order-item {
      background-color: #ffffff;
      border-radius: 16rpx;
      margin-bottom: 20rpx;
      padding: 30rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      
      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 20rpx;
        border-bottom: 1rpx solid #f0f0f0;
        
        .shop-info {
          display: flex;
          align-items: center;
          
          .shop-name {
            font-size: 28rpx;
            color: #333;
            margin-left: 10rpx;
          }
        }
        
        .order-status {
          font-size: 26rpx;
          padding: 6rpx 12rpx;
          border-radius: 20rpx;
          
          &.status-pending {
            color: #ff9800;
            background-color: rgba(255, 152, 0, 0.1);
          }
          
          &.status-paid {
            color: #2196f3;
            background-color: rgba(33, 150, 243, 0.1);
          }
          
          &.status-shipped {
            color: #9c27b0;
            background-color: rgba(156, 39, 176, 0.1);
          }
          
          &.status-completed {
            color: #4caf50;
            background-color: rgba(76, 175, 80, 0.1);
          }
          
          &.status-cancelled {
            color: #9e9e9e;
            background-color: rgba(158, 158, 158, 0.1);
          }
          
          &.status-refunding {
            color: #f44336;
            background-color: rgba(244, 67, 54, 0.1);
          }
        }
      }
      
      .order-goods {
        display: flex;
        padding: 20rpx 0;
        
        .goods-image {
          width: 160rpx;
          height: 160rpx;
          border-radius: 8rpx;
          background-color: #f5f5f5;
          flex-shrink: 0;
        }
        
        .goods-info {
          flex: 1;
          margin-left: 20rpx;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          
          .goods-name {
            font-size: 28rpx;
            color: #333;
            line-height: 1.4;
            margin-bottom: 10rpx;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }
          
          .goods-specs {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 10rpx;
          }
          
          .goods-price-count {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .goods-price {
              font-size: 28rpx;
              color: #333;
              font-weight: 500;
            }
            
            .goods-count {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
      }
      
      .order-amount {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f0f0f0;
        
        .amount-text {
          font-size: 26rpx;
          color: #666;
        }
        
        .amount-value {
          font-size: 30rpx;
          color: #ff4444;
          font-weight: 500;
          margin: 0 6rpx;
        }
        
        .amount-shipping {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .order-actions {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-top: 20rpx;
        gap: 20rpx;
        
        .action-btn {
          padding: 10rpx 20rpx;
          border-radius: 30rpx;
          font-size: 26rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          
          &.btn-primary {
            background-color: #ff4444;
            color: #ffffff;
          }
          
          &.btn-secondary {
            background-color: #ffffff;
            color: #666666;
            border: 1rpx solid #dddddd;
          }
        }
      }
    }
  }
  </style> -->
  <template>
    <view class="submitorder-container">
      <!-- 自定义导航栏 -->
      <view class="custom-navbar">
        <view class="navbar-left" @click="goBack">
          <u-icon name="arrow-left" size="20" color="#333"></u-icon>
        </view>
        <view class="navbar-title">提交订单</view>
        <view class="navbar-right">
          <u-icon name="more-dot-fill" size="20" color="#333" @click="showMoreOptions"></u-icon>
          <u-icon name="minus" size="20" color="#333" @click="minimize"></u-icon>
          <u-icon name="target" size="20" color="#333" @click="showTarget"></u-icon>
        </view>
      </view>
  
      <!-- 地址选择 -->
      <view class="address-section" @click="selectAddress">
        <view class="address-content">
          <view class="address-left">
            <u-icon name="map-pin" size="24" color="#ff4444"></u-icon>
            <view class="address-info">
              <view class="address-text">{{addressInfo.username}} {{addressInfo.address}}</view>
              <view class="phone-text">{{addressInfo.phone}}</view>
            </view>
          </view>
          <view class="address-right">
            <u-icon name="arrow-right" size="20" color="#999"></u-icon>
          </view>
        </view>
      </view>
  
      <!-- 商品信息 -->
      <view class="product-section">
        <view class="shop-info">
          <u-icon name="shopping-cart" size="16" color="#333"></u-icon>
          <text class="shop-name">{{productInfo.shopName}}</text>
        </view>
        
        <view class="product-item">
          <image class="product-image" :src="productInfo.image" mode="aspectFill"></image>
          <view class="product-info">
            <view class="product-name">{{productInfo.name}}</view>
            <view class="product-specs" v-if="productInfo.specs">{{productInfo.specs}}</view>
            <view class="product-quantity">数量:{{productInfo.quantity}}</view>
            <view class="product-price">¥ {{productInfo.price}}</view>
          </view>
        </view>
        
        <!-- 订单选项 -->
        <view class="order-options">
          <view class="option-item" @click="selectDeliveryService">
            <text class="option-label">配送服务</text>
            <view class="option-right">
              <text class="option-value">{{deliveryService}}</text>
              <u-icon name="arrow-right" size="16" color="#999"></u-icon>
            </view>
          </view>
          
          <view class="option-item">
            <text class="option-label">配送费用</text>
            <view class="option-right">
              <text class="option-value">¥ {{deliveryFee}}</text>
            </view>
          </view>
          
          <view class="option-item" @click="selectStoreCoupon">
            <text class="option-label">店铺优惠券</text>
            <view class="option-right">
              <text class="option-value coupon-value">- ¥ {{storeCoupon}}</text>
              <u-icon name="arrow-right" size="16" color="#999"></u-icon>
            </view>
          </view>
          
          <view class="option-item" @click="addOrderNote">
            <text class="option-label">订单备注</text>
            <view class="option-right">
              <text class="option-value">{{orderNote || '选填'}}</text>
              <u-icon name="arrow-right" size="16" color="#999"></u-icon>
            </view>
          </view>
          
          <view class="option-item" @click="selectInvoice">
            <text class="option-label">开具发票</text>
            <view class="option-right">
              <text class="option-value">{{invoiceText}}</text>
              <u-icon name="arrow-right" size="16" color="#999"></u-icon>
            </view>
          </view>
        </view>
      </view>
  
      <!-- 价格明细 -->
      <view class="price-section">
        <view class="section-title">价格明细</view>
        
        <view class="price-item">
          <text class="price-label">平台优惠券</text>
          <view class="price-right">
            <text class="price-value coupon-value">-¥{{platformCoupon}}</text>
            <u-icon name="arrow-right" size="16" color="#999"></u-icon>
          </view>
        </view>
        
        <view class="price-item">
          <text class="price-label">积分抵扣</text>
          <view class="price-right">
            <u-checkbox 
              v-model="usePoints" 
              @change="togglePoints"
              shape="circle"
              size="20"
            ></u-checkbox>
            <text class="points-text">{{usePoints ? '使用积分抵扣' : '不使用积分抵扣'}}</text>
          </view>
        </view>
        
        <view class="price-item">
          <text class="price-label">商品总价</text>
          <view class="price-right">
            <text class="price-value">¥{{totalProductPrice}}</text>
          </view>
        </view>
        
        <view class="price-item">
          <text class="price-label">店铺优惠</text>
          <view class="price-right">
            <text class="price-value coupon-value">-¥{{storeDiscount}}</text>
          </view>
        </view>
      </view>
  
      <!-- 底部提交栏 -->
      <view class="footer-bar">
        <view class="footer-left">
          <view class="total-info">
            共{{totalQuantity}}件 合计:¥<text class="total-price">{{totalAmount}}</text>
          </view>
          <view class="discount-info">共优惠 ¥{{totalDiscount}}元</view>
        </view>
        <view class="footer-right">
          <u-button 
            type="primary" 
            size="large" 
            @click="submitOrder"
            :loading="submitting"
          >提交订单</u-button>
        </view>
      </view>
    </view>
  </template>
  
  <script>
  import { getUserId } from '../../utils/auth.js';
  import { get, post, del, put } from '../../utils/request.js';
  import { getAddressById, getDefaultAddress, formatAddress } from '../../utils/addressApi.js';
  
  export default {
    name: 'SubmitOrder',
    data() {
      return {
        submitting: false,
        usePoints: false,
        addressInfo: {
          address: '',
          phone: '',
          username: ''
        },
        productInfo: {
          shopName: 'Mall4j蓝海商城',
          name: '',
          quantity: 0,
          price: '0.00',
          image: '',
          specs: ''
        },
        deliveryService: '快递配送',
        deliveryFee: '0.00',
        storeCoupon: '0.00',
        orderNote: '',
        invoiceText: '本次不开具发票',
        platformCoupon: '0.00',
        totalProductPrice: '0.00',
        storeDiscount: '0.00',
        totalQuantity: 0,
        totalAmount: '0.00',
        totalDiscount: '0.00',
        userId: Number(getUserId()),
        orderData: null
      }
    },
    async onLoad(options) {
      console.log('订单提交页面加载，接收参数:', options);
      
      try {
        await this.initPageData(options);
        
        if (!options.productId) {
          this.find();
        }
      } catch (error) {
        console.error('页面初始化失败:', error);
        this.loadDefaultAddress();
      }
    },
    methods: {
      goBack() {
        uni.navigateBack();
      },
      
      goToLogin() {
        uni.navigateTo({
          url: '/pages/login/login'
        });
      },
  
      async find() {
        try {
          const res = await get('/orderst/list',{});
          if (res && res.code === 200) {
            let orderData = res.data || res.rows || [];
            
            if (Array.isArray(orderData) && orderData.length > 0) {
              let submitorder = orderData[0];
              
              this.addressInfo.address = submitorder.useraddress || '';
              this.addressInfo.username = submitorder.username || '';
              this.addressInfo.phone = submitorder.userphone || '';
              
              this.productInfo.name = submitorder.goodsname || '';
              this.productInfo.image = submitorder.goodsimg || '';
              this.productInfo.specs = submitorder.goodsSpecs || '';
              this.productInfo.quantity = parseInt(submitorder.goodsnumber) || 0;
              this.productInfo.price = submitorder.goodsprice || '0.00';
              
              this.orderNote = submitorder.orderComment || '';
              this.totalProductPrice = (parseFloat(submitorder.goodsprice || 0) * parseInt(submitorder.goodsnumber || 0)).toFixed(2);
              this.deliveryFee = (parseFloat(submitorder.orderPostPrice || 0)).toFixed(2);
              this.totalQuantity = parseInt(submitorder.goodsnumber) || 0;
              
              this.calculateTotal();
              
              this.orderData = submitorder;
            } else {
              this.loadDefaultAddress();
            }
          }
        } catch (error) {
          console.error('获取订单列表失败:', error);
          uni.showToast({
            title: '获取订单列表失败',
            icon: 'none'
          });
        }
      },
      
      showMoreOptions() {
        uni.showActionSheet({
          itemList: ['刷新', '设置', '帮助'],
          success: (res) => {
            console.log('选择了第' + (res.tapIndex + 1) + '个选项')
          }
        })
      },
      
      minimize() {
        console.log('最小化')
      },
      
      showTarget() {
        console.log('显示目标')
      },
      
      async initPageData(options) {
        console.log('订单提交页面接收参数:', options);
        
        if (options.productId) {
          this.loadProductInfoFromParams(options);
        }
        
        if (options.addressId) {
          await this.loadAddressInfo(options.addressId);
        } else {
          await this.loadDefaultAddress();
        }
        
        if (!options.productId) {
          this.find();
        }
      },
      
      loadProductInfoFromParams(options) {
        try {
          this.productInfo = {
            ...this.productInfo,
            name: options.productName || '商品名称',
            image: options.productImage || '/static/logo.png',
            specs: options.productSpecs || '',
            quantity: parseInt(options.productQuantity) || 1,
            price: options.productPrice || '0.00'
          };
          
          this.deliveryFee = (parseFloat(options.shipping) || 0).toFixed(2);
          
          this.totalProductPrice = (parseFloat(this.productInfo.price) * this.productInfo.quantity).toFixed(2);
          this.totalQuantity = this.productInfo.quantity;
          
          this.calculateTotal();
          
          this.orderData = {
            productId: options.productId,
            productName: options.productName,
            productImage: options.productImage,
            productPrice: options.productPrice,
            productSpecs: options.productSpecs,
            productQuantity: options.productQuantity,
            productSkuId: options.productSkuId,
            businessId: options.businessId,
            shipping: options.shipping
          };
        } catch (error) {
          console.error('从URL参数加载商品信息失败:', error);
          this.find();
        }
      },
      
      async loadAddressInfo(addressId) {
        try {
          const response = await getAddressById(addressId);
          
          if (response && response.code === 200 && response.data) {
            const addressData = response.data;
            
            this.addressInfo = {
              id: addressData.id,
              province: addressData.province,
              city: addressData.city,
              county: addressData.county,
              content: addressData.content,
              username: addressData.userName,
              phone: addressData.phone,
              address: formatAddress(addressData)
            };
          } else {
            this.loadDefaultAddress();
          }
        } catch (error) {
          console.error('加载地址信息失败:', error);
          this.loadDefaultAddress();
        }
      },
      
      loadDefaultAddress() {
        const defaultAddress = getDefaultAddress();
        
        this.addressInfo = {
          id: defaultAddress.id,
          province: defaultAddress.province,
          city: defaultAddress.city,
          county: defaultAddress.county,
          content: defaultAddress.content,
          username: defaultAddress.userName,
          phone: defaultAddress.phone,
          address: formatAddress(defaultAddress)
        };
      },
      
      selectAddress() {
        uni.navigateTo({
          url: '/pages/address/address?select=true',
          events: {
            addressSelected: (addressData) => {
              this.addressInfo = {
                id: addressData.id,
                province: addressData.province,
                city: addressData.city,
                county: addressData.county,
                content: addressData.content,
                username: addressData.userName,
                phone: addressData.phone,
                address: `${addressData.province}${addressData.city}${addressData.county}${addressData.content}`
              };
            }
          },
          success: () => {
            console.log('跳转到地址选择页面');
          },
          fail: (err) => {
            console.error('跳转地址选择页面失败:', err);
            uni.showToast({
              title: '跳转失败',
              icon: 'none'
            });
          }
        });
      },
      
      selectDeliveryService() {
        uni.showActionSheet({
          itemList: ['快递配送', '到店自提', '同城配送'],
          success: (res) => {
            const services = ['快递配送', '到店自提', '同城配送']
            this.deliveryService = services[res.tapIndex]
            this.calculateTotal()
          }
        })
      },
      
      selectStoreCoupon() {
        uni.navigateTo({
          url: '/pages/coupon/coupon?select=true'
        })
      },
      
      addOrderNote() {
        uni.showModal({
          title: '订单备注',
          editable: true,
          placeholderText: '请输入订单备注',
          content: this.orderNote,
          success: (res) => {
            if (res.confirm) {
              this.orderNote = res.content
            }
          }
        })
      },
      
      selectInvoice() {
        uni.showActionSheet({
          itemList: ['本次不开具发票', '开具普通发票', '开具专用发票'],
          success: (res) => {
            const invoices = ['本次不开具发票', '开具普通发票', '开具专用发票']
            this.invoiceText = invoices[res.tapIndex]
          }
        })
      },
      
      togglePoints(value) {
        this.usePoints = value
        this.calculateTotal()
      },
      
      calculateTotal() {
        let total = parseFloat(this.totalProductPrice)
        
        total -= parseFloat(this.storeCoupon)
        total -= parseFloat(this.platformCoupon)
        total += parseFloat(this.deliveryFee)
        
        if (this.usePoints) {
          total -= 0
        }
        
        this.totalAmount = total.toFixed(2)
        this.totalDiscount = (parseFloat(this.totalProductPrice) - total).toFixed(2)
      },
      
      async submitOrder() {
        if (!this.addressInfo.address) {
          uni.showToast({
            title: '请选择收货地址',
            icon: 'none'
          })
          return
        }
        
        this.submitting = true
        
        try {
          // 构造要传递的订单数据
          const orderData = {
            userId: this.userId,
            goodsName: this.productInfo.name,
            goodsPrice: this.productInfo.price,
            goodsQuantity: this.productInfo.quantity,
            goodsImage: this.productInfo.image,
            goodsSpecs: this.productInfo.specs,
            totalAmount: this.totalAmount,
            deliveryFee: this.deliveryFee,
            addressInfo: this.addressInfo,
            orderNote: this.orderNote,
            deliveryService: this.deliveryService
          };
          
          // 编码为URL参数
          const queryParams = Object.keys(orderData)
            .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(JSON.stringify(orderData[key]))}`)
            .join('&');
          
          // 跳转到订单列表页并传递数据
          uni.navigateTo({
            url: `/pages/order/order-list?fromSubmit=1&${queryParams}`
          });
          
        } catch (error) {
          console.error('提交订单失败:', error);
          uni.showToast({
            title: '提交订单失败',
            icon: 'none'
          });
        } finally {
          this.submitting = false;
        }
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .submitorder-container {
    min-height: 100vh;
    background-color: #f8f8f8;
    padding-bottom: 120rpx;
  }
  
  .custom-navbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    background-color: #ffffff;
    border-bottom: 1rpx solid #f0f0f0;
    
    .navbar-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .navbar-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333333;
    }
    
    .navbar-right {
      display: flex;
      align-items: center;
      gap: 20rpx;
      
      .u-icon {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
  
  .address-section {
    background-color: #ffffff;
    margin: 20rpx;
    border-radius: 20rpx;
    padding: 30rpx;
    
    .address-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .address-left {
        display: flex;
        align-items: flex-start;
        gap: 20rpx;
        flex: 1;
        
        .address-info {
          .address-text {
            font-size: 32rpx;
            font-weight: 600;
            color: #333333;
            margin-bottom: 10rpx;
            line-height: 1.4;
          }
          
          .phone-text {
            font-size: 28rpx;
            color: #999999;
          }
        }
      }
      
      .address-right {
        width: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
  
  .product-section {
    background-color: #ffffff;
    margin: 20rpx;
    border-radius: 20rpx;
    padding: 30rpx;
    
    .shop-info {
      display: flex;
      align-items: center;
      gap: 10rpx;
      margin-bottom: 20rpx;
      
      .shop-name {
        font-size: 28rpx;
        color: #333333;
      }
    }
    
    .product-item {
      display: flex;
      gap: 20rpx;
      margin-bottom: 30rpx;
      
      .product-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 10rpx;
        background-color: #f5f5f5;
      }
      
      .product-info {
        flex: 1;
        
        .product-name {
          font-size: 28rpx;
          color: #333333;
          margin-bottom: 10rpx;
          line-height: 1.4;
        }
        
        .product-specs {
          font-size: 24rpx;
          color: #999999;
          margin-bottom: 10rpx;
        }
        
        .product-quantity {
          font-size: 24rpx;
          color: #999999;
          margin-bottom: 15rpx;
        }
        
        .product-price {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
        }
      }
    }
    
    .order-options {
      .option-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .option-label {
          font-size: 28rpx;
          color: #333333;
        }
        
        .option-right {
          display: flex;
          align-items: center;
          gap: 10rpx;
          
          .option-value {
            font-size: 28rpx;
            color: #666666;
            
            &.coupon-value {
              color: #ff4444;
            }
          }
        }
      }
    }
  }
  
  .price-section {
    background-color: #ffffff;
    margin: 20rpx;
    border-radius: 20rpx;
    padding: 30rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
      margin-bottom: 20rpx;
    }
    
    .price-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .price-label {
        font-size: 28rpx;
        color: #333333;
      }
      
      .price-right {
        display: flex;
        align-items: center;
        gap: 10rpx;
        
        .price-value {
          font-size: 28rpx;
          color: #333333;
          
          &.coupon-value {
            color: #ff4444;
          }
        }
        
        .points-text {
          font-size: 28rpx;
          color: #666666;
        }
      }
    }
  }
  
  .footer-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
    padding: 20rpx 30rpx;
    border-top: 1rpx solid #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .footer-left {
      .total-info {
        font-size: 28rpx;
        color: #333333;
        margin-bottom: 5rpx;
        
        .total-price {
          font-size: 36rpx;
          font-weight: 600;
          color: #ff4444;
        }
      }
      
      .discount-info {
        font-size: 24rpx;
        color: #ff4444;
      }
    }
    
    .footer-right {
      .u-button {
        width: 200rpx;
        height: 80rpx;
        border-radius: 40rpx;
        background-color: #ff4444;
        border: none;
        
        &::after {
          border: none;
        }
      }
    }
  }
  </style>